package com.bestdreamer.synch.account2;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock 锁
 */
public class AccountLock {

    // 定义锁对象
    private final ReentrantLock lock = new ReentrantLock();

    // 封装账户编号、账户余额两个 Field
    private String accountNo;
    private double balance;

    public AccountLock(){}

    public AccountLock(String accountNo, double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }
    public String getAccountNo() {
        return accountNo;
    }
    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    // 因为账户余额不允许随意修改，所以只为 balance 提供 getter 方法
    public double getBalance(){
        return this.balance;
    }

    /**
     * 提供一个线程安全的 draw() 方法来完成取钱操作
     */
    public void draw(double drawAmount){
        // 账户余额大于取钱数目
        lock.lock();
        try{
            if( balance >= drawAmount ){
                System.out.println( Thread.currentThread().getName() + "取钱成功！取出钞票："+ drawAmount);
                try{
                    Thread.sleep(1);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                balance -= drawAmount;
                System.out.println("\t 余额为："+balance);
            }else {
                System.out.println(Thread.currentThread().getName()+"取钱失败！余额不足啊！");
            }
        }finally {
            // 修改完成，释放锁
            lock.unlock();
        }

    }

    public int hashCode(){
        return accountNo.hashCode();
    }

    public boolean equals(Object obj){
        if(this == obj){
            return true;
        }
        if( obj != null && obj.getClass() == AccountLock.class){
            AccountLock target = (AccountLock)obj;
            return target.getAccountNo().equals(accountNo);
        }
        return false;
    }

}
